package com.ruoyi.common.utils.reflect

import com.ruoyi.common.core.text.Convert.toBool
import com.ruoyi.common.core.text.Convert.toDouble
import com.ruoyi.common.core.text.Convert.toFloat
import com.ruoyi.common.core.text.Convert.toInt
import com.ruoyi.common.core.text.Convert.toLong
import com.ruoyi.common.core.text.Convert.toStr
import com.ruoyi.common.utils.DateUtils.parseDate
import org.apache.commons.lang3.StringUtils
import org.apache.commons.lang3.Validate
import org.apache.poi.ss.usermodel.DateUtil
import org.slf4j.LoggerFactory
import java.lang.reflect.*
import java.util.*

/**
 * 反射工具类. 提供调用getter/setter方法, 访问私有变量, 调用私有方法, 获取泛型类型Class, 被AOP过的真实类等工具函数.
 *
 * @author ruoyi
 */
object ReflectUtils {
    private const val SETTER_PREFIX = "set"
    private const val GETTER_PREFIX = "get"
    private const val CGLIB_CLASS_SEPARATOR = "$$"
    private val logger = LoggerFactory.getLogger(ReflectUtils::class.java)

    /**
     * 调用Getter方法.
     * 支持多级，如：对象名.对象名.方法
     */
    fun <E> invokeGetter(obj: Any?, propertyName: String?): E? {
        var `object` = obj
        for (name in StringUtils.split(propertyName, ".")) {
            val getterMethodName = GETTER_PREFIX + StringUtils.capitalize(name)
            `object` = invokeMethod<Any>(`object`, getterMethodName, arrayOf(), arrayOf())
        }
        return `object` as E?
    }

    /**
     * 调用Setter方法, 仅匹配方法名。
     * 支持多级，如：对象名.对象名.方法
     */
    fun <E> invokeSetter(obj: Any?, propertyName: String?, value: E) {
        var `object` = obj
        val names = StringUtils.split(propertyName, ".")
        for (i in names.indices) {
            if (i < names.size - 1) {
                val getterMethodName = GETTER_PREFIX + StringUtils.capitalize(names[i])
                `object` = invokeMethod<Any>(`object`, getterMethodName, arrayOf(), arrayOf())
            } else {
                val setterMethodName = SETTER_PREFIX + StringUtils.capitalize(names[i])
                invokeMethodByName<Any>(`object`, setterMethodName, arrayOf(value))
            }
        }
    }

    /**
     * 直接读取对象属性值, 无视private/protected修饰符, 不经过getter函数.
     */
    fun <E> getFieldValue(obj: Any, fieldName: String): E? {
        val field = getAccessibleField(obj, fieldName)
        if (field == null) {
            logger.debug("在 [" + obj.javaClass + "] 中，没有找到 [" + fieldName + "] 字段 ")
            return null
        }
        var result: E? = null
        try {
            result = field[obj] as E
        } catch (e: IllegalAccessException) {
            logger.error("不可能抛出的异常{}", e.message)
        }
        return result
    }

    /**
     * 直接设置对象属性值, 无视private/protected修饰符, 不经过setter函数.
     */
    fun <E> setFieldValue(obj: Any, fieldName: String, value: E) {
        val field = getAccessibleField(obj, fieldName)
        if (field == null) {
            // throw new IllegalArgumentException("在 [" + obj.getClass() + "] 中，没有找到 [" + fieldName + "] 字段 ");
            logger.debug("在 [" + obj.javaClass + "] 中，没有找到 [" + fieldName + "] 字段 ")
            return
        }
        try {
            field[obj] = value
        } catch (e: IllegalAccessException) {
            logger.error("不可能抛出的异常: {}", e.message)
        }
    }

    /**
     * 直接调用对象方法, 无视private/protected修饰符.
     * 用于一次性调用的情况，否则应使用getAccessibleMethod()函数获得Method后反复调用.
     * 同时匹配方法名+参数类型，
     */
    fun <E> invokeMethod(obj: Any?, methodName: String?, parameterTypes: Array<Class<*>?>,
                         args: Array<Any?>): E? {
        if (obj == null || methodName == null) {
            return null
        }
        val method = getAccessibleMethod(obj, methodName, *parameterTypes)
        if (method == null) {
            logger.debug("在 [" + obj.javaClass + "] 中，没有找到 [" + methodName + "] 方法 ")
            return null
        }
        return try {
            method.invoke(obj, *args) as E
        } catch (e: Exception) {
            val msg = "method: $method, obj: $obj, args: $args"
            throw convertReflectionExceptionToUnchecked(msg, e)
        }
    }

    /**
     * 直接调用对象方法, 无视private/protected修饰符，
     * 用于一次性调用的情况，否则应使用getAccessibleMethodByName()函数获得Method后反复调用.
     * 只匹配函数名，如果有多个同名函数调用第一个。
     */
    fun <E> invokeMethodByName(obj: Any?, methodName: String, args: Array<Any?>): E? {
        val method = getAccessibleMethodByName(obj, methodName, args.size)
        if (method == null) {
            // 如果为空不报错，直接返回空。
            logger.debug("在 [" + obj!!.javaClass + "] 中，没有找到 [" + methodName + "] 方法 ")
            return null
        }
        return try {
            // 类型转换（将参数数据类型转换为目标方法参数类型）
            val cs = method.parameterTypes
            for (i in cs.indices) {
                if (args[i] != null && args[i]!!.javaClass != cs[i]) {
                    if (cs[i] == String::class.java) {
                        args[i] = toStr(args[i])
                        if (StringUtils.endsWith(args[i] as String?, ".0")) {
                            args[i] = StringUtils.substringBefore(args[i] as String?, ".0")
                        }
                    } else if (cs[i] == Int::class.java) {
                        args[i] = toInt(args[i])
                    } else if (cs[i] == Long::class.java) {
                        args[i] = toLong(args[i])
                    } else if (cs[i] == Double::class.java) {
                        args[i] = toDouble(args[i])
                    } else if (cs[i] == Float::class.java) {
                        args[i] = toFloat(args[i])
                    } else if (cs[i] == Date::class.java) {
                        if (args[i] is String) {
                            args[i] = parseDate(args[i])
                        } else {
                            args[i] = DateUtil.getJavaDate((args[i] as Double?)!!)
                        }
                    } else if (cs[i] == Boolean::class.javaPrimitiveType || cs[i] == Boolean::class.java) {
                        args[i] = toBool(args[i])
                    }
                }
            }
            method.invoke(obj, *args) as E
        } catch (e: Exception) {
            val msg = "method: $method, obj: $obj, args: $args"
            throw convertReflectionExceptionToUnchecked(msg, e)
        }
    }

    /**
     * 循环向上转型, 获取对象的DeclaredField, 并强制设置为可访问.
     * 如向上转型到Object仍无法找到, 返回null.
     */
    fun getAccessibleField(obj: Any?, fieldName: String): Field? {
        // 为空不报错。直接返回 null
        if (obj == null) {
            return null
        }
        Validate.notBlank(fieldName, "fieldName can't be blank")
        var superClass: Class<*> = obj.javaClass
        while (superClass != Any::class.java) {
            return try {
                val field = superClass.getDeclaredField(fieldName)
                makeAccessible(field)
                field
            } catch (e: NoSuchFieldException) {
                superClass = superClass.superclass
                continue
            }
            superClass = superClass.superclass
        }
        return null
    }

    /**
     * 循环向上转型, 获取对象的DeclaredMethod,并强制设置为可访问.
     * 如向上转型到Object仍无法找到, 返回null.
     * 匹配函数名+参数类型。
     * 用于方法需要被多次调用的情况. 先使用本函数先取得Method,然后调用Method.invoke(Object obj, Object... args)
     */
    fun getAccessibleMethod(obj: Any?, methodName: String,
                            vararg parameterTypes: Class<*>?): Method? {
        // 为空不报错。直接返回 null
        if (obj == null) {
            return null
        }
        Validate.notBlank(methodName, "methodName can't be blank")
        var searchType: Class<*> = obj.javaClass
        while (searchType != Any::class.java) {
            return try {
                val method = searchType.getDeclaredMethod(methodName, *parameterTypes)
                makeAccessible(method)
                method
            } catch (e: NoSuchMethodException) {
                searchType = searchType.superclass
                continue
            }
            searchType = searchType.superclass
        }
        return null
    }

    /**
     * 循环向上转型, 获取对象的DeclaredMethod,并强制设置为可访问.
     * 如向上转型到Object仍无法找到, 返回null.
     * 只匹配函数名。
     * 用于方法需要被多次调用的情况. 先使用本函数先取得Method,然后调用Method.invoke(Object obj, Object... args)
     */
    fun getAccessibleMethodByName(obj: Any?, methodName: String, argsNum: Int): Method? {
        // 为空不报错。直接返回 null
        if (obj == null) {
            return null
        }
        Validate.notBlank(methodName, "methodName can't be blank")
        var searchType: Class<*> = obj.javaClass
        while (searchType != Any::class.java) {
            val methods = searchType.declaredMethods
            for (method in methods) {
                if (method.name == methodName && method.parameterTypes.size == argsNum) {
                    makeAccessible(method)
                    return method
                }
            }
            searchType = searchType.superclass
        }
        return null
    }

    /**
     * 改变private/protected的方法为public，尽量不调用实际改动的语句，避免JDK的SecurityManager抱怨。
     */
    fun makeAccessible(method: Method) {
        if ((!Modifier.isPublic(method.modifiers) || !Modifier.isPublic(method.declaringClass.modifiers))
                && !method.isAccessible) {
            method.isAccessible = true
        }
    }

    /**
     * 改变private/protected的成员变量为public，尽量不调用实际改动的语句，避免JDK的SecurityManager抱怨。
     */
    fun makeAccessible(field: Field) {
        if ((!Modifier.isPublic(field.modifiers) || !Modifier.isPublic(field.declaringClass.modifiers)
                        || Modifier.isFinal(field.modifiers)) && !field.isAccessible) {
            field.isAccessible = true
        }
    }

    /**
     * 通过反射, 获得Class定义中声明的泛型参数的类型, 注意泛型必须定义在父类处
     * 如无法找到, 返回Object.class.
     */
    fun <T> getClassGenricType(clazz: Class<*>): Class<T> {
        return getClassGenricType(clazz, 0) as Class<T>
    }

    /**
     * 通过反射, 获得Class定义中声明的父类的泛型参数的类型.
     * 如无法找到, 返回Object.class.
     */
    fun getClassGenricType(clazz: Class<*>, index: Int): Class<*> {
        val genType = clazz.genericSuperclass
        if (genType !is ParameterizedType) {
            logger.debug(clazz.simpleName + "'s superclass not ParameterizedType")
            return Any::class.java
        }
        val params = genType.actualTypeArguments
        if (index >= params.size || index < 0) {
            logger.debug("Index: " + index + ", Size of " + clazz.simpleName + "'s Parameterized Type: "
                    + params.size)
            return Any::class.java
        }
        if (params[index] !is Class<*>) {
            logger.debug(clazz.simpleName + " not set the actual class on superclass generic parameter")
            return Any::class.java
        }
        return params[index] as Class<*>
    }

    fun getUserClass(instance: Any?): Class<*> {
        if (instance == null) {
            throw RuntimeException("Instance must not be null")
        }
        val clazz: Class<*> = instance.javaClass
        if (clazz.name.contains(CGLIB_CLASS_SEPARATOR)) {
            val superClass = clazz.superclass
            if (superClass != null && Any::class.java != superClass) {
                return superClass
            }
        }
        return clazz
    }

    /**
     * 将反射时的checked exception转换为unchecked exception.
     */
    fun convertReflectionExceptionToUnchecked(msg: String?, e: Exception?): RuntimeException {
        if (e is IllegalAccessException || e is IllegalArgumentException
                || e is NoSuchMethodException) {
            return IllegalArgumentException(msg, e)
        } else if (e is InvocationTargetException) {
            return RuntimeException(msg, e.targetException)
        }
        return RuntimeException(msg, e)
    }
}
